import userCenterBaseInfoApi from '@/api/userCenter/userCenterBaseInfoApi'
import userCenterLogoutApi from '@/api/userCenter/userCenterLogoutApi'
import { getAppNav } from '@/App'
import LocalStorageKey from '@/constant/LocalStorageKey'
import ISocketMessage from '@/model/other/ISocketMessage'
import IMenuVO from '@/model/vo/menu/IMenuVO'
import IUserBaseInfoVO from '@/model/vo/user/IUserBaseInfoVO'
import { useAppDispatch, useAppSelector } from '@/store'
import {
  setLoadMenuFlag,
  setSocketMessage,
  setSocketStatus,
} from '@/store/common/commonSlice'
import { setUserBaseInfo, setUserMenuList } from '@/store/user/userSlice'
import { execConfirm, ToastSuccess } from '@/util/CommonUtil'
import { closeSocket, connectionSocket } from '@/util/Socket'
import { logout } from '@/util/UserUtil'
import { Button } from 'antd-mobile'
import { Dispatch, SetStateAction, useEffect, useState } from 'react'

export default function Center() {
  const [jwt, setJwt] = useState(localStorage.getItem(LocalStorageKey.JWT)) // 触发：页面更新机制

  return jwt ? <CenterElement setJwt={setJwt} /> : <CenterNoLoginElement />
}

interface ICenterElement {
  setJwt: Dispatch<React.SetStateAction<string | null>>
}

// 个人中心的页面元素
function CenterElement(props: ICenterElement) {
  const userBaseInfo = useAppSelector((state) => state.user.userBaseInfo)
  const socketMessage = useAppSelector((state) => state.common.socketMessage) // socket消息模板
  const appDispatch = useAppDispatch()

  // 更新 userBaseInfo
  function doSetUserBaseInfo(userBaseInfo: IUserBaseInfoVO) {
    appDispatch(setUserBaseInfo(userBaseInfo))
  }

  // 更新 redux里面 socket的值
  function doSetSocketMessage(params: ISocketMessage) {
    appDispatch(setSocketMessage(params))
  }

  // 更新 redux里面 socket的状态
  function doSetSocketStatus(params: boolean) {
    appDispatch(setSocketStatus(params))
  }

  useEffect(() => {
    // 获取用户基本信息
    userCenterBaseInfoApi()
      .then(({ data }) => {
        doSetUserBaseInfo(data.data)
      })
      .catch(() => {
        props.setJwt(null) // 触发页面更新
      })
    connectionSocket(doSetSocketMessage, doSetSocketStatus) // 连接 socket
  }, [])

  useEffect(() => {
    if (
      socketMessage.code === 2 ||
      socketMessage.code === 3 ||
      socketMessage.code === 4
    ) {
      props.setJwt(null) // 触发页面更新
    }
  }, [socketMessage.code])

  return (
    <div className="wh100 flex-c ai-c jc-c">
      {userBaseInfo.nickname}
      <div className="m-t-10">
        <Button
          onClick={() => {
            logoutClick(props.setJwt)
          }}
        >
          退出登录
        </Button>
      </div>
    </div>
  )
}

function logoutClick(setJwt: Dispatch<SetStateAction<string | null>>) {
  execConfirm(
    () => {
      return userCenterLogoutApi().then(({ data }) => {
        ToastSuccess(data.msg, 2)
        logout()
        setJwt(null)
      })
    },
    undefined,
    '确定退出登录吗？'
  )
}

// 没有登录时的页面元素
function CenterNoLoginElement() {
  const appDispatch = useAppDispatch()

  useEffect(() => {
    // 清除登录信息
    localStorage.clear()
    sessionStorage.clear()
    appDispatch(setUserBaseInfo({}))
    // 重置：用户菜单
    appDispatch(setUserMenuList([] as IMenuVO[]))
    // 设置：是否加载过菜单为 false
    appDispatch(setLoadMenuFlag(false))
    // 关闭 socket
    closeSocket()
  }, [])

  return (
    <div className="flex-center wh100">
      <Button onClick={() => getAppNav()('/login')}>立即登录</Button>
    </div>
  )
}
